<template>
  <view class="tabs">
    <scroll-view ref="tabbar1" id="tab-bar" class="tab-bar" :scroll-x="true" :show-scrollbar="false" :enable-flex="true"
      :scroll-into-view="scrollInto">
      <!-- <view style="flex-direction: row; display: flex; height: 100%"> -->
      <view class="uni-tab-item" v-for="(tab, index) in tabList" :key="tab.id" :id="tab.id" :ref="'tabitem' + index"
        :data-id="index" :data-current="index" @click="ontabtap">
        <text class="uni-tab-item-title" :class="tabIndex == index ? 'uni-tab-item-title-active' : ''">{{ tab.name
          }}</text>
      </view>
      <!-- </view> -->
    </scroll-view>
    <swiper class="tab-view" ref="swiper1" id="tab-bar-view" :current="tabIndex" :duration="300"
      @change="onswiperchange" @animationfinish="animationfinish" @onAnimationEnd="animationfinish">
      <swiper-item class="swiper-item" v-for="(page, index) in tabList" :key="index">
        <swiperPage class="swiper-page" :type="page.type" ref="page" @switchTab="switchTab" @refreshList="refreshList">
        </swiperPage>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
// 缓存每页最多
const MAX_CACHE_DATA = 100;

// 缓存页签数量
const MAX_CACHE_PAGE = 3;
const TAB_PRELOAD_OFFSET = 1;

import swiperPage from './swiper-page.vue';
import uniIcons from '@/components/uni-icons/uni-icons.vue';
import { orderStateList } from '@/utils/common';

export default {
  components: {
    swiperPage,
    uniIcons
  },
  data() {
    return {
      tabList: [],
      tabIndex: '',
      cacheTab: [],
      scrollInto: "",
      isTap: true,
    }
  },
  onLoad(option) {
    const { type } = option || {};
    let idx = 0;
    for (let i = 0; i < orderStateList.length; i++) {
      if (`${type}` === `${orderStateList[i].type}`) {
        idx = i;
      }
      this.tabList.push({
        id: "tab" + i,
        name: orderStateList[i].name,
        type: orderStateList[i].type,
        icon: orderStateList[i].icon,
      })
    };
    this.tabIndex = idx;
  },
  onReady() {
    this._lastTabIndex = 0;
    this.swiperWidth = 0;
    this.tabbarWidth = 0;
    this.tabListSize = {};
    this._touchTabIndex = 0;

    // #ifndef MP-ALIPAY
    this.pageList = this.$refs.page;
    // #endif
    this.loadTabData(this.tabIndex);

    this.getTabbarItemsSize();
  },
  onShow() {
    if (typeof this.tabIndex === 'number') {
      this.loadTabData(this.tabIndex);
    }
  },
  methods: {
    ontabtap(e) {
      let index = e.target.dataset.current || e.currentTarget.dataset.current;

      // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      this.isTap = true;
      var currentSize = this.tabListSize[index];
      this._touchTabIndex = index;
      // #endif

      this.switchTab(index);
    },
    onswiperchange(e) {
      // 注意：百度小程序会触发2次

      // #ifndef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      let index = e.target.current || e.detail.current;
      this.switchTab(index);
      // #endif
    },
    onswiperscroll(e) {
      if (this.isTap) { return;}

      var offsetX = e.detail.dx;
      var preloadIndex = this._lastTabIndex;
      if (offsetX > TAB_PRELOAD_OFFSET) {
        preloadIndex++;
      } else if (offsetX < -TAB_PRELOAD_OFFSET) {
        preloadIndex--;
      }
      if (preloadIndex === this._lastTabIndex || preloadIndex < 0 || preloadIndex > this.pageList.length - 1) {
        return;
      }
      if (this.pageList[preloadIndex].dataList.length === 0) {
        this.loadTabData(preloadIndex);
      }
    },
    animationfinish(e) {
      // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      let index = e.detail.current;
      if (this._touchTabIndex === index) {
        this.isTap = false;
      }
      this._lastTabIndex = index;
      this.switchTab(index);
      // #endif
    },
    getTabbarItemsSize() {
      uni.createSelectorQuery().in(this).select('.tab-view').fields({
        dataset: true,
        size: true,
      }, (res) => {
        this.swiperWidth = res.width;
      }).exec();
      uni.createSelectorQuery().in(this).selectAll('.uni-tab-item').boundingClientRect((rects) => {
        rects.forEach((rect) => {
          this.tabListSize[rect.dataset.id] = rect;
        })
      }).exec();
    },
    switchTab(index) {
      if (this.tabIndex === index) {
        return;
      }

      this.loadTabData(index);

      // // 缓存 tabId
      // if (this.pageList[this.tabIndex].dataList.length > MAX_CACHE_DATA) {
      //   let isExist = this.cacheTab.indexOf(this.tabIndex);
      //   if (isExist < 0) {
      //     this.cacheTab.push(this.tabIndex);
      //   }
      // }

      this.tabIndex = index;

      this.scrollInto = this.tabList[index].id;

      // // 释放 tabId
      // if (this.cacheTab.length > MAX_CACHE_PAGE) {
      //   let cacheIndex = this.cacheTab[0];
      //   this.clearTabData(cacheIndex);
      //   this.cacheTab.splice(0, 1);
      // }
    },
    scrollTabTo(index) {
      const el = this.$refs['tabitem' + index][0];
      let offset = 0;
      // TODO fix ios offset
      if (index > 0) {
        offset = this.tabbarWidth / 2 - this.tabListSize[index].width / 2;
        if (this.tabListSize[index].right < this.tabbarWidth / 2) {
          offset = this.tabListSize[0].width;
        }
      }
      dom.scrollToElement(el, {
        offset: -offset
      });
    },
    loadTabData(index) {
      this.pageList?.[index]?.loadData?.();
    },
    clearTabData(index) {
      this.pageList[index].clear();
    },
    refreshList() {
      this.loadTabData(this.tabIndex);
    },
  },
  onShareAppMessage(res) {
    const { dataset } = res.target || {};
    const { name } = dataset || {};
    const { orderStoreVo, orderId } = name || {};
    const { orderProductVoList } = orderStoreVo || {};
    const { name: Title = '', image = '', productId } = orderProductVoList?.[0] || {};
    const shareObj = {
      title: Title,
      path: `/pages/agreement/index?id=${productId}&recommendId=${uni.getStorageSync('userId')}&recommendOrderId=${orderId}`,
      imageUrl: image,
    }
    const promise = new Promise(resolve => {
      setTimeout(() => {
        uni.$u.toast('分享成功')
      }, 1000)
      resolve(shareObj)
    })
    if (res.from === 'button') {// 来自页面内分享按钮
      return {
        ...shareObj,
        promise,
      }
    }
    return {
      path: '/pages/index/index',
      promise: new Promise(resolve => {
        setTimeout(() => {
          uni.$u.toast('分享成功')
        }, 1000)
        resolve({
          path: '/pages/index/index',
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* #ifndef APP-PLUS */
page {
  width: 100%;
  min-height: 100%;
  display: flex;
}

/* #endif */

.tabs {
  flex: 1;
  flex-direction: column;
  overflow: hidden;
  background-color: #ffffff;
  height: 100vh;
}

.tab-bar {
  width: 100vw;
  height: 112rpx;
  display: flex;
  flex-direction: row;
  /* #ifndef APP-PLUS */
  white-space: nowrap;
  /* #endif */
}

/* #ifndef APP-NVUE */
.tab-bar ::-webkit-scrollbar {
  display: none;
  width: 0 !important;
  height: 0 !important;
  -webkit-appearance: none;
  background: transparent;
}

/* #endif */

.tab-view {
  flex: 1;
  height: calc(100% - 112rpx);
}

.uni-tab-item {
  flex-wrap: nowrap;
  width: 30vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.uni-tab-item-title {
  color: #000;
  font-size: 32rpx;
  flex-wrap: nowrap;
  /* #ifndef APP-PLUS */
  white-space: nowrap;
  /* #endif */
  line-height: 112rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uni-tab-item-title-active {
  font-weight: bolder;
  font-size: 36rpx;
}

.uni-tab-item-title-active::after {
  position: absolute;
  bottom: 0;
  content: ' ';
  height: 8rpx;
  width: 88rpx;
  border-radius: 2rpx;
  background-color: #79C435;
}

.swiper-item {
  flex: 1;
  flex-direction: column;
}

.swiper-page {
  flex: 1;
  flex-direction: row;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}
</style>